package com.only4play.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.only4play.common.model.GeneralResponse;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author liyuncong
 * @version 1.0
 * @file HttpUtils
 * @brief http请求工具类
 * @details http请求工具类
 * @date 2023-11-18
 * <p>
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2023-11-18               liyuncong          Created
 */
public class HttpUtils {

    private static RestTemplate restTemplate;
    private static final ObjectMapper objectMapper = new ObjectMapper();


    public HttpUtils(RestTemplate template) {
        if (Objects.nonNull(template)) {
            restTemplate = template;
        }else {
            restTemplate = new RestTemplate();
        }
    }

    public HttpUtils() {
        restTemplate = new RestTemplate();
    }

    public static String get(String url, Map<String, String> requestParam) {
        GeneralResponse response = restTemplate.getForObject(url, GeneralResponse.class, requestParam);
        try {
            return objectMapper.writeValueAsString(response);
        } catch (Exception exception) {
            return null;
        }
    }

    public static String post(String url, Map<String, String> requestBody) {
        GeneralResponse generalResponse = restTemplate.postForObject(url, requestBody, GeneralResponse.class);
        try {
            return objectMapper.writeValueAsString(generalResponse);
        } catch (Exception exception) {
            return null;
        }
    }

    public static String post(String url, Map<String, String> requestParam, Map<String, String> requestBody, Map<String, String> header) {
        GeneralResponse generalResponse = restTemplate.postForObject(url, requestBody, GeneralResponse.class);
        try {
            return objectMapper.writeValueAsString(generalResponse);
        } catch (Exception exception) {
            return null;
        }
    }

    public static String postHeader(String url, Map<String, String> header) {
        return post(url, new IdentityHashMap<>(), null, header);
    }
}
